/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { constants } from "./constants.js";
import { BranchNode } from "./BranchNode.js";
import { isRunning } from "./helper.js";
"use strict";

var __importDefault = this && this.__importDefault || function (mod) {
    return mod && mod.__esModule ? mod : { "default": mod };
};

const constants_1 = constants;
const BranchNode_1 = __importDefault(BranchNode);
// const helper_1 = helper;
class Random extends BranchNode_1.default {
    constructor() {
        super(...arguments);
        this.nodeType = 'Random';
    }
    run(blackboard = {}, { lastRun, introspector, rerun, registryLookUp = x => x } = {}) {
        let currentIndex = 0;
        if (rerun) {
            currentIndex = lastRun.state.findIndex(x => (0, isRunning)(x));
        } else {
            this.blueprint.start(blackboard);
            currentIndex = Math.floor(Math.random() * this.numNodes);
        }
        const node = registryLookUp(this.nodes[currentIndex]);
        const result = node.run(blackboard, { lastRun, introspector, rerun, registryLookUp });
        const running = (0, isRunning)(result);
        if (!running) {
            this.blueprint.end(blackboard);
        }
        if (introspector) {
            const debugResult = running ? constants_1.RUNNING : result;
            introspector.wrapLast(1, this, debugResult, blackboard);
        }
        if (running) {
            const returningResult = { total: constants_1.RUNNING, state: new Array(this.numNodes).fill(undefined) };
            returningResult.state[currentIndex] = result;
            return returningResult;
        }
        return result;
    }
}
export { Random }
// exports.default = Random;